package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.constants.CacheNameConstants;
import info.batcloud.fanli.core.entity.UserAuthorize;
import info.batcloud.fanli.core.enums.Authorize;
import info.batcloud.fanli.core.repository.UserAuthorizeRepository;
import info.batcloud.fanli.core.repository.UserRepository;
import info.batcloud.fanli.core.service.UserAuthorizeService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = CacheNameConstants.USER_AUTHORIZE)
public class UserAuthorizeServiceImpl implements UserAuthorizeService {

    @Inject
    private UserAuthorizeRepository userAuthorizeRepository;

    @Inject
    private UserRepository userRepository;

    @Inject
    private UserAuthorizeService userAuthorizeService;

    @Override
    @CacheEvict(key = "'USER_AUTHORIZE_LIST' + #userId")
    public void addAuthorize(long userId, Authorize authorize) {
        if (userAuthorizeRepository.countByUserIdAndAuthorize(userId, authorize) > 0) {
            return;
        }
        UserAuthorize ua = new UserAuthorize();
        ua.setUser(userRepository.findOne(userId));
        ua.setAuthorize(authorize);
        ua.setCreateTime(new Date());
        userAuthorizeRepository.save(ua);
    }

    @Override
    public boolean checkAuthorize(long userId, Authorize authorize) {

        return userAuthorizeService.findByUserId(userId).contains(authorize);
    }

    @Override
    @Cacheable(key = "'USER_AUTHORIZE_LIST' + #userId")
    public List<Authorize> findByUserId(long userId) {
        return userAuthorizeRepository.findByUserId(userId).stream().map(o -> o.getAuthorize()).collect(Collectors.toList());
    }

    @Override
    @CacheEvict(key = "'USER_AUTHORIZE_LIST' + #userId")
    @Transactional
    public void deleteAuthorize(long userId, Authorize authorize) {
        this.userAuthorizeRepository.deleteByUserIdAndAuthorize(userId, authorize);
    }

    @Override
    @Transactional
    public void deleteById(long id) {
        this.userAuthorizeService.deleteById(id);
    }
}
